interface LocationResponse {
  location_id: string;
  cn_name: string;
  en_name: string;
  parent_id: string;
  cn_location_type: string;
  en_location_type: string;
}

const locationResponses: LocationResponse[] = [
  {
    location_id: "1",
    cn_name: "小明1",
    en_name: "xiaoming",
    parent_id: "0",
    cn_location_type: "广州",
    en_location_type: "guangzhou",
  },
  {
    location_id: "2",
    cn_name: "小明2",
    en_name: "xiaoming",
    parent_id: "1",
    cn_location_type: "广州",
    en_location_type: "guangzhou",
  },
  {
    location_id: "3",
    cn_name: "小明3",
    en_name: "xiaoming",
    parent_id: "1",
    cn_location_type: "广州",
    en_location_type: "guangzhou",
  },
  {
    location_id: "4",
    cn_name: "小明3",
    en_name: "xiaoming",
    parent_id: "2",
    cn_location_type: "广州",
    en_location_type: "guangzhou",
  },
  {
    location_id: "5",
    cn_name: "小明1",
    en_name: "xiaoming",
    parent_id: "0",
    cn_location_type: "广州",
    en_location_type: "guangzhou",
  },
];

interface IRetLocationResponses {
  location_id: string;
  cn_name: string;
  en_name: string;
  parent_id: string;
  cn_location_type: string;
  en_location_type: string;
  children: LocationResponse[];
}

/**
 * 扁平数组转为树形结构
 * @param locationResponses
 * @returns
 */
const flatArrToTree = (
  locationResponses: LocationResponse[]
): IRetLocationResponses[] => {
  const ret: IRetLocationResponses[] = [];

  // 存放已经加入到结果中的location_id
  const map = new Map<string, IRetLocationResponses>();

  locationResponses.forEach((item) => {
    const { location_id, parent_id } = item;
    let newItem: IRetLocationResponses = {
      ...item,
      children: [],
    };
    if (!map.has(parent_id)) {
      // 没有父亲
      ret.push(newItem);
    } else {
      // 存在父亲
      const parent = map.get(parent_id)!;
      parent.children.push(newItem);
    }

    // 加入map中
    map.set(location_id, newItem);
  });

  return ret;
};

console.log(flatArrToTree(locationResponses));
